package com.example.task1.ui.AllService.traffic;

import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.task1.R;
import com.example.task1.application.MyApplication;
import com.example.task1.bean.TrafficCartListBean;
import com.example.task1.http.Api;
import com.example.task1.util.ApiResp;
import com.example.task1.util.CallBack;

import retrofit2.Call;

public class TrafficCartActivity extends AppCompatActivity {

    private int id;
    private RecyclerView rvList;
    private Button btnSave;
    private TrafficCartListAdapter mTrafficCartListAdapter;

    @Override
    protected void onRestart() {
        super.onRestart();
        initData();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_traffic_cart);
        ActionBar supportActionBar = getSupportActionBar();
        supportActionBar.setTitle("车辆");
        supportActionBar.setDisplayHomeAsUpEnabled(true);
        id = getIntent().getIntExtra("id", 0);
        initView();
        initData();
        setAdapter();
        business();
    }

    private void business() {
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyApplication.intent(TrafficCartActivity.this, TrafficModificationCartActivity.class, 1);
            }
        });
    }

    private void setAdapter() {
        mTrafficCartListAdapter = new TrafficCartListAdapter(this, id);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        rvList.setLayoutManager(linearLayoutManager);
        rvList.setAdapter(mTrafficCartListAdapter);
    }

    private void initData() {
        Call<ApiResp> apiRespCall = Api.api().get(MyApplication.TOKEN, "/prod-api/api/traffic/car/list");
        Api.send(apiRespCall, TrafficCartListBean.class, new CallBack<TrafficCartListBean>() {
            @Override
            public void success(TrafficCartListBean data) {
                mTrafficCartListAdapter.setData(data.getRows());
            }

            @Override
            public void error(String msg) {

            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    private void initView() {
        rvList = (RecyclerView) findViewById(R.id.rv_list);
        btnSave = (Button) findViewById(R.id.btn_save);
        if (id != 0) {
            btnSave.setVisibility(View.GONE);
        }
    }
}